package com.cygia.springbootserver.controller;

import static org.assertj.core.api.Assertions.assertThat;
import com.alibaba.fastjson.JSON;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cygia.springbootserver.entity.User;
import com.cygia.springbootserver.mapper.UserMapper;
import common.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserMapper userMapper;

    /**
     * 查询用户
     *
     * @param pageNum  当前页码
     * @param pageSize 每页多少条
     * @param search   查询字符
     * @return page
     */
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {

        // 分页一
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(User::getUsername, search);
        }
//        Page<User> page = userMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
////        Page<Map<String, Object>> page = userMapper.selectMapsPage(new Page<>(pageNum, pageSize), wrapper);
//        Integer count = userMapper.selectCount(null);
//        page.setTotal(count);
//        page.setSize(pageSize);
//        page.setPages(pageNum);


        //分页二
//        Integer offset = (pageNum - 1) * pageSize;// 从0开始，第一页0~9，第二页10~19，偏移量=（当前页码-1）*10
//        List<User> userData = null;
//        if (search.isEmpty() || search.length() == 0) {
//            userData = userMapper.findByPage(offset, pageSize);
//        } else {
//            userData = userMapper.findByPage(offset, pageSize, search);
//        }
//        Integer count = userMapper.countUser();
//        com.cygia.springbootserver.vo.Page<User> page = new Page<>();
//        page.setRecords(userData);
//        page.setTotal(count);
//        page.setPageNum(pageNum);
//        page.setPageSize(pageSize);
//        System.out.println(page);

        // 分页三
        Page<User> page = new Page<>(pageNum, pageSize);
        page.addOrder(OrderItem.asc("username"));
        Page<User> userIPage = userMapper.selectPage(page, wrapper); // Wrappers.<User>lambdaQuery().eq(User::getAge, 20).like(User::getName, "Jack")
        assertThat(page).isSameAs(userIPage);
        System.out.println("总条数 -------------> {}"+userIPage.getTotal());
        System.out.println("当前页数 -------------> {}"+userIPage.getCurrent());
        System.out.println("当前每页显示数 -------------> {}"+userIPage.getSize());
        List<User> records = userIPage.getRecords();
        assertThat(records).isNotEmpty();

        // json 正反序列化
        String json = JSON.toJSONString(page);
        System.out.println("json ----------> {}"+ json);
        Page<User> page1 = JSON.parseObject(json, new TypeReference<Page<User>>() {});
        List<User> records1 = page1.getRecords();
        assertThat(records1).isNotEmpty();
        assertThat(records1.get(0).getClass()).isEqualTo(User.class);

        return Result.success(userIPage);
    }

    /**
     * 添加or更新用户
     *
     * @param user
     * @return
     */
    @PostMapping("/save")
    public Result<?> save(@RequestBody User user) {
        if (user == null) {
            return Result.error(10002, "用户不存在，创建失败！");
        }
        if (user.getUsername().isEmpty() || user.getAddress().isEmpty()) {
            System.out.println("用户名和地址为空，创建失败！");
            return Result.error(10001, "用户名和地址为空，创建失败！");
        }
        if (user.getId() != null) {
            System.out.println("更新用户：" + user);
            userMapper.updateById(user);
        } else {
            System.out.println("添加用户：" + user);
            userMapper.insert(user);
        }
        return Result.success();
    }


    /**
     * 删除用户
     */
    @DeleteMapping("/delUser/{id}")
    public Result<?> deleteUserById(@PathVariable Long id) {
        userMapper.deleteById(id);
        return Result.success();
    }

}
